import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class ServicePage extends StatefulWidget {
  @override
  _ServicePageState createState() => _ServicePageState();
}

class _ServicePageState extends State<ServicePage> {
  var text = "";
  var text2 = "";
  static const platform = const MethodChannel('com.example.flutter.study');

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initChannel();
  }
@override
  void dispose() async{
    // TODO: implement dispose
    super.dispose();
    await platform
        .invokeMethod("closeTimer", {"name": "closeTimer"});
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("原生与flutter互相调用"),
      ),
      body: Column(
        children: [
          ElevatedButton(
            child: Text("flutter给原生Android传值"),
            onPressed: () async {
              var data = await platform
                  .invokeMethod("getAndroidData", {"name": "getAndroidData"});
              print("count:$data");
              setState(() {
                text = data;
              });
            },
          ),
          Text(text),
          ElevatedButton(
            child: Text("Android调用flutter的方法进行传值"),
            onPressed: () async {
              var data = await platform
                  .invokeMethod("getService", {"name": "getAndroidData"});
            },
          ),
          Text(text2)
        ],
      ),
    );
  }

  void _initChannel() {
    var channel = MethodChannel("com.example.flutter.study");
    channel.setMethodCallHandler((call) {
      // 同样也是根据方法名分发不同的函数
      switch (call.method) {
        case "sendCount":
          {
            String msg = call.arguments["count"];
            setState(() {
              text2 = msg;
            });
          }
          break;
      }
      return null;
    });
  }
}
